import Vue from 'vue'
import VueRouter from 'vue-router'
//导入对应的页面组件，登录，我的，视频，文章
import MyLogin from '@/views/MyLogin'
import Layout from '@/views/Layout'
//二级路由组件
import MyHome from '@/views/MyHome'
import MyMine from '@/views/MyMine'
import MineChat from '@/views/MyMine/MineChat'
import MyAsk from '@/views/MyAsk'
import MyVideo from '@/views/MyVideo'
import MySearch from '@/views/MySearch'
import MyResult from '@/views/MySearch/MyResult'
//导入我的编辑页
import MineEdit from '@/views/MyMine/MineEdit'
// import { getToken } from '@/utils/auth'
import MyArticle from '@/views/MyArticle'
import { Toast } from 'vant'
import store from '@/store'

// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [{
  name: 'chat',
  path: '/mine/chat',
  component: MineChat
},
{
  name: 'result',
  path: '/search/result',
  component: MyResult
},
{
  name: 'MySearch',
  path: '/search',
  component: MySearch
},
{
  name: 'MyArticle',
  path: '/article',
  component: MyArticle
},
//路由重定向
{ path: '/', redirect: '/layout/home' },
{ name: 'login', path: '/login', component: MyLogin },
//做成一级路由
{
  name: 'edit', path: '/mine/edit',
  component: MineEdit,
  //这个页面也需要登录，所以添加meta对象的needLogin属性即可
  meta: {
    needLogin: true
  }
},
// layout一级路由
{
  name: 'Layout',
  path: '/layout',
  component: Layout,
  children: [
    //首页是不用登录的，其他页面都需要登录才能看
    {
      name: 'home', path: 'home', component: MyHome, meta: {
        needKeep: true
      }
    },
    //以下需要登录的页面用路由元信息对象
    {
      name: 'mine', path: 'mine',
      component: MyMine,
      meta: {
        needLogin: true
      }
    },
    {
      name: 'ask', path: 'ask',
      component: MyAsk,
      meta: {
        needLogin: true
      }
    },
    {
      name: 'video',
      path: 'video',
      component: MyVideo,
      meta: {
        needLogin: true
      }
    },
  ]
}

]



const router = new VueRouter({
  routes
})

//路由重定向，全局路由前置守卫，进入路由跳转前触发
//to要去哪里，有要去哪里的路由信息
//from从哪里来，有从哪里来的路由信息
//next相当于router.push放行
router.beforeEach((to, from, next) => {
  //如果要去的页面需要登录
  if (to.meta.needLogin) {
    //需要登录，判断有无token，有token说明登录了放行，没有直接去登录页
    if (store.state.tokenObj.token) {
      //代表登录了放行
      next()
    } else {
      //说明没有token
      Toast('请先登录')
      //打回登录页时携带登录的参数
      next({
        name: 'login',
        //用query
        query: {
          //参数名叫做back
          //参数值就是我原本想去的路劲
          back: to.path
        }
      })
    }
  } else {
    // 代表去的页面不需要登录直接放行
    next()
  }


})

export default router
